package com.tsinkai.ettp.controller.wx;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Hex;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/wxcheck")
public class WxCheckTokenController {
	
	String token = "test";
	
	/*
	 * 微信url接入验证
	 */
	@RequestMapping(value = "/token",method = RequestMethod.GET)
	public String checkToken(HttpServletRequest req) {
		String signature = null;
		String echostr = null;
		String hexString = null;
		try {
			signature = req.getParameter("signature");
			String timestamp = req.getParameter("timestamp");
			String nonce = req.getParameter("nonce");
			echostr = req.getParameter("echostr");
			
			String[] arr = {token,timestamp,nonce};
			Arrays.sort(arr);
			String conArrStr = arr[0] + arr[1] +arr[2];
			
			try {
				MessageDigest md = MessageDigest.getInstance("SHA-1");
				hexString = Hex.encodeHexString(md.digest(conArrStr.getBytes()));
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		boolean result = false;
		if(hexString!=null) {
			result = hexString.equals(signature);
		}
		if(result) {
			System.out.println("返回echostr："+echostr);
			return echostr;
		}else {
			System.out.println("校验失败");
			return "校验失败";
		}
		
		
	}

	/*
	 * 微信消息处理
	 */
	@RequestMapping(value = "/token",method = RequestMethod.POST)
	public Object hadleMessage() {
		return null;
	}
}


